package com.kim.bookshop.user.serviceimpl;

import java.util.List;

import com.kim.bookshop.user.bean.User;
import com.kim.bookshop.user.dao.UserDao;
import com.kim.bookshop.user.service.UserService;
import exception.BookShopException;

public class UserServiceImpl implements UserService {
	private UserDao userDao;

	@Override
	public void register(User form) throws BookShopException {
		//校验用户名
		User user=userDao.findByUsername(form.getUserName());
		if(user!=null) throw new BookShopException("用户名已被注册");
		//校验邮箱
		user=userDao.findByEmail(form.getEmail());
		if(user!=null) throw new BookShopException("该Email已被注册过");
		//插入
		userDao.add(form);
	}

	@Override
	public void active(String code) throws BookShopException {
		//使用code查询数据库，得到user
				User user=userDao.findByCode(code);
				if(user==null) throw new BookShopException("激活无效！！！");
				if(user.getState()==1) throw new BookShopException("你已经激活过了！！！不用再次激活");
				userDao.updateState(user.getUid(), 1);
	}

	@Override
	public User login(User form) throws BookShopException{
		User user=userDao.findByUsername(form.getUserName());
		System.out.println(form);
		if(user==null) throw new BookShopException("用户名不存在");
		if(!user.getPassword().equals(form.getPassword())) throw new BookShopException("密码错误");
		if(user.getState()==0) throw new BookShopException("该账户未激活");
		if(user.getState()==2) throw new BookShopException("此用户已被禁用");
		return user;
	}

	@Override
	public void admin(User form) throws BookShopException{
		User admin=userDao.adminLogin(form.getUserName());
		if(admin==null) throw new BookShopException("用户名不存在");
		if(!admin.getPassword().equals(form.getPassword())) throw new BookShopException("密码错误");
		if(admin.getRole()!=1) throw new BookShopException("此账户不是管理员身份");
	}

	@Override
	public List<User> getList() {
		return userDao.getList();
	}

	@Override
	public void updatemsg(User user) {
		userDao.updatemsg(user);
	}

	@Override
	public void kill(String uid) {
		userDao.kill(uid);
	}

	@Override
	public User load(String uid) {
		return userDao.load(uid);
	}

	@Override
	public List<User> getAdmin() {
		return userDao.getAdmin();
	}

	@Override
	public void restart(String uid) {
		userDao.restart(uid);
		
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public void remove(String uid) {
		userDao.delete(uid);
	}
	
	
}
